<!--
 * @Description: 上传图片
 * 
 * @Author: XiongYaoYuan<xiongyaoyuan>
 * @Date: 2023-07-08 22:50:22
 * @FilePath: /yuxiuproweb/src/views/mes/pro/workorder/mods/add/image.vue
-->
<template>
  <el-dialog
    :close-on-click-modal="false"
    v-dialogDrag
    title="图片"
    :visible.sync="shows"
    width="500px"
    append-to-body
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="50px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="粘贴">
            <el-input
              class="mb10 input-layout"
              type="textarea"
              :rows="2"
              placeholder="粘贴图片即可上传"
              v-model="image"
              @paste.native="handlePaste"
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="图" prop="picture">
            <image-upload v-model="form.picture" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="shows = false">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  props: {
    show: Boolean,
    data: {
      type: Object,
    },
  },
  data() {
    return {
      // 表单参数
      form: {
        picture: null,
      },
      // 表单校验
      rules: {},
      image: null,
    };
  },
  computed: {
    shows: {
      get() {
        return this.show;
      },
      set(newValue) {
        this.$emit("update:show", newValue);
      },
    },
  },
  created() {
    if (this.data) {
      this.form.picture = this.data.picture;
    }
  },
  methods: {
    async handlePaste(value) {
      let file = value.clipboardData.items[0];
      if (file.type.includes("image")) {
        let imgFile = file.getAsFile();
        const formData = new FormData();
        formData.append("file", imgFile);

        const url = `http://www.lewei.com/dev-api/common/uploadMinio`;
        const resp = await fetch(url, {
          method: "POST",
          body: formData,
        });
        const res = await resp.json();
        const fileList = this.form.picture?.split(",") || [];
        fileList.push(res.url);
        this.form.picture = fileList.join();
      }
    },
    /** 提交按钮 */
    async submitForm() {
      try {
        this.$emit("on-change", this.form);
        this.shows = false;
      } catch (e) {
        console.log(e);
      }
    },
  },
};
</script>
